package collection;

import java.util.Iterator;

import exception.CollectionEmptyException;

public class UnOrdTree<E> extends ATree<UnOrdTreeNode<E>, E> {

	private UnOrdTreeNode<E> root = null;
	private int size = 0;
	
	public UnOrdTree() {}

	@Override
	public UnOrdTreeNode<E> createNode(E element) 
	{
		return new UnOrdTreeNode<E>(element);
	}

	@Override
	public boolean isInternal(UnOrdTreeNode<E> someNode) 
	{
		return getChildren(someNode).iterator().hasNext();
	}

	@Override
	public boolean isExternal(UnOrdTreeNode<E> someNode) 
	{
		return !isInternal(someNode);
	}

	@Override
	public UnOrdTreeNode<E> getParent(UnOrdTreeNode<E> someNode) 
	{
		return someNode.getParent();
	}
	
	public void setParent(UnOrdTreeNode<E> someNode, UnOrdTreeNode<E> parentNode)
	{
		someNode.setParent(parentNode);
	}

	@Override
	public Iterable<UnOrdTreeNode<E>> getChildren(final UnOrdTreeNode<E> someNode) 
	{
		return new Iterable<UnOrdTreeNode<E>>()
				{

					@Override
					public Iterator<UnOrdTreeNode<E>> iterator() 
					{
						return someNode.getChildren().elementsIterator();
					}
					
				};
	}
	
	public void addChild(UnOrdTreeNode<E> someNode, UnOrdTreeNode<E> childNode)
	{
		someNode.addChild(childNode);
		childNode.setParent(someNode);
		this.size += 1;
	}
	
	public void addChildElement(UnOrdTreeNode<E> someNode, E element)
	{
		addChild(someNode, createNode(element));
		this.size += 1;
	}

	@Override
	public int size() 
	{
		return this.size;
	}

	@Override
	public UnOrdTreeNode<E> getRoot() throws CollectionEmptyException 
	{
		if (isEmpty())
			throw new CollectionEmptyException("UnOrdered Tree");
		else
			return this.root;
	}

	@Override
	public UnOrdTreeNode<E> createRoot(E element) 
	{
		this.root = new UnOrdTreeNode<E>(element);
		this.size += 1;
		return root;
	}

	@Override
	public boolean isRoot(UnOrdTreeNode<E> someNode) 
	{
		return someNode == this.root;
	}

}
